use printpdf::*;
use std::fs::{self, File};
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use ::image::ImageReader;

/// 支持的图片格式扩展名
const SUPPORTED_EXTENSIONS: &[&str] = &["jpg", "jpeg", "png", "bmp", "gif", "tiff"];

/// 从文件夹创建PDF
pub fn folder_to_pdf(folder_path: &str, output_file: &str) -> Result<(), Box<dyn std::error::Error>> {
    let path = Path::new(folder_path);
    if !path.exists() || !path.is_dir() {
        return Err("Invalid folder path".into());
    }

    // 获取所有支持的图片文件
    let mut image_paths: Vec<PathBuf> = Vec::new();
    for entry in fs::read_dir(path)? {
        let entry = entry?;
        let path = entry.path();
        if let Some(extension) = path.extension() {
            if let Some(ext) = extension.to_str() {
                if SUPPORTED_EXTENSIONS.contains(&ext.to_lowercase().as_str()) {
                    image_paths.push(path);
                }
            }
        }
    }

    // 按文件名排序
    image_paths.sort();

    if image_paths.is_empty() {
        return Err("No supported image files found in the folder".into());
    }

    // 转换图片路径为字符串切片
    let image_paths_str: Vec<&str> = image_paths
        .iter()
        .filter_map(|p| p.to_str())
        .collect();

    // 调用现有的 images_to_pdf 函数
    images_to_pdf(&image_paths_str, output_file)?;

    Ok(())
}

pub fn images_to_pdf(image_paths: &[&str], output_path: &str) -> Result<(), Box<dyn std::error::Error>> {
    // A4纸张尺寸为210mm x 297mm
    let page_width = 210.0f32;
    let page_height = 297.0f32;
    
    // 定义页面边距（单位：毫米）
    let margin = 10.0f32;  // 设置 10mm 的边距
    let content_width = page_width - 2.0 * margin;
    let content_height = page_height - 2.0 * margin;
    
    // 使用更合适的 DPI 值
    let pdi = 300.0;
    let px_to_mm = 25.4 / pdi;  // 使用 300 DPI 获得更好的质量
    
    // 创建一个新的PDF文档
    let (doc, page1, layer1) = PdfDocument::new("Image PDF", Mm(page_width), Mm(page_height), "Layer 1");

    // 遍历所有图片
    for (index, image_path) in image_paths.iter().enumerate() {
        // 为每张图片创建新页面
        let current_layer = if index == 0 {
            doc.get_page(page1).get_layer(layer1)
        } else {
            let (page, layer1) = doc.add_page(Mm(page_width), Mm(page_height), format!("Layer {}", index + 1));
            doc.get_page(page).get_layer(layer1)
        };

        // 读取图片
        let img = ImageReader::open(image_path)?.decode()?;
        let img_rgb = img.to_rgb8();
        
        // 将图片转换为PDF图像
        let image = Image::from(ImageXObject {
            width: Px(img_rgb.width() as usize),
            height: Px(img_rgb.height() as usize),
            color_space: ColorSpace::Rgb,
            bits_per_component: ColorBits::Bit8,
            interpolate: true,
            image_data: img_rgb.into_raw(),
            image_filter: None,
            clipping_bbox: None,
            smask: None,
        });
        
        // 计算缩放比例，确保图片完整显示且居中
        let img_width = img.width() as f32;
        let img_height = img.height() as f32;
        let img_aspect = img_width / img_height;
        let content_aspect = content_width / content_height;
        
        // 计算合适的缩放比例，使图片尽可能大但不超出内容区域
        let (scale, translate_x, translate_y) = if img_aspect > content_aspect {
            // 图片比内容区域更宽，以宽度为准进行缩放
            let scale = content_width / (img_width * px_to_mm);
            let scaled_height = img_height * scale * px_to_mm;
            // 计算垂直居中的位置
            let y_offset = margin + (content_height - scaled_height) / 2.0;
            
            (scale, margin, y_offset)
        } else {
            // 图片比内容区域更高，以高度为准进行缩放
            let scale = content_height / (img_height * px_to_mm);
            let scaled_width = img_width * scale * px_to_mm;
            let scaled_height = img_height * scale * px_to_mm;
            // 水平和垂直都居中
            let x_offset = (page_width - scaled_width) / 2.0;
            let y_offset = margin + (content_height - scaled_height) / 2.0;
            
            (scale, x_offset, y_offset)
        };

        // 创建图像变换
        let transform = ImageTransform {
            translate_x: Some(Mm(translate_x)),
            translate_y: Some(Mm(translate_y)),
            rotate: None,
            scale_x: Some(scale),
            scale_y: Some(scale),
            dpi: Some(300.0),  // 设置较高的 DPI 值以获得更好的质量
        };

        // 在PDF中放置图片
        image.add_to_layer(current_layer, transform);
    }

    // 保存PDF文件
    let file = File::create(Path::new(output_path))?;
    let mut writer = BufWriter::new(file);
    doc.save(&mut writer)?;

    Ok(())
}
